package org.example.slave.util;

import cn.hutool.core.util.ArrayUtil;
import lombok.Data;

import java.io.IOException;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description
 */
@Data
public class LengthCodedStringReader {

    public static final String CODE_PAGE_1252 = "UTF-8";

    private String encoding;
    private int index = 0; // 数组下标

    public LengthCodedStringReader(String encoding, int startIndex) {
        this.encoding = encoding;
        this.index = startIndex;
    }

    public String readLengthCodedString(byte[] data) throws IOException {
        byte[] lengthBytes = ByteUtil.readBinaryCodedLengthBytes(data, this.getIndex());
        long length = ByteUtil.readLengthCodedBinary(data, getIndex());
        setIndex(getIndex() + lengthBytes.length);
        if (ByteUtil.NULL_LENGTH == length) {
            return null;
        }

        try {
            return new String(ArrayUtil.sub(data, getIndex(), (int) (getIndex() + length)), encoding == null ? CODE_PAGE_1252 : encoding);
        } finally {
            setIndex((int) (getIndex() + length));
        }
    }
}
